# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : lijikai1206@163.com
# @Time : 2021/3/7 22:57 
# @File : psutil_op.py
import os

import psutil


def get_pid(pname):
    pid = None
    for proc in psutil.process_iter():
        # print(“pid-%d,name:%s” % (proc.pid,proc.name()))
        if proc.name() == pname:
            pid = proc.pid
    return pid
class PsutilProcess:
    def get_proinfo(self):
        psutil.test()
        self.p_info_list = []
        for p in psutil.process_iter(attrs=['pid', 'name']):
            # print(p.info)
            self.p_info_list.append(p.info)
        return self.p_info_list

    def query_pid(self, fname):
        pid_lst = []
        for info in self.p_info_list:
            if info['name'] == fname:
                pid_lst.append(info['pid'])
        return pid_lst


    def pid_detal(self, pid):
        self.p = psutil.Process(pid)
        return self.p

    def get_cwd(self):
        dir_path = self.p.cwd()
        return dir_path

    def get_cur_pid(self):
        cur_pid = self.p.pid()
        return cur_pid

    def get_parent_pid(self):
        parent_pid = self.p.ppid()
        return parent_pid

    def get_child_pid(self):
        child_pid = self.p.children()
        return child_pid

    def get_status(self):
        status = self.p.status()
        return status

    def get_uids(self):
        '''
        执行进程的用户id
        '''
        user_id = self.p.uids()
        return user_id

    def get_gids(self):
        '''
        执行进程的组id
        '''
        group_id = self.p.gids()
        return group_id

    def get_cpu_time(self):
        cpu_time = self.p.cpu_times()
        return cpu_time

    def close_terminal(self):
        self.p.terminate()
        return True


def use_psutil(prc_path, proc_name='cmd.exe'):
    flag = False
    pp = PsutilProcess()
    pp.get_proinfo()
    pid_lst = pp.query_pid(fname=proc_name)
    if len(pid_lst) > 0:
        for pid in pid_lst:
            pp.pid_detal(pid)
            cwd_path = pp.get_cwd()
            print(cwd_path)
            if os.path.normcase(prc_path) == os.path.normcase(cwd_path):
                pp.close_terminal()
                flag = True
                break
    else:
        flag = True
    return flag


if __name__ == '__main__':
    path_key = "FSK-数据库升级包"
    # use_psutil(path_key)
    res = get_pid('my_job')
    print('res:', res)
